package zxs.sino.elite.hub.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 阿里云短信服务
 *
 * @author zhang
 */
@Component
public class AliSMSUtil {

    @Value("${aliyun.access-key}")
    private String accessKey;

    @Value("${aliyun.secret-key}")
    private String secretKey;

    @Value("${aliyun.sms.region}")
    private String region;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;


    /**
     * 发送短信验证码
     *
     * @param phone 手机号
     * @param code  验证码
     */
    public Map<String, Object> doSendSMSCode(String phone, String code) {


        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKey)
                .accessKeySecret(secretKey)
                .build());

        AsyncClient client = AsyncClient.builder()
                .region(region)
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com"))
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(phone)
                .templateParam("{\"code\":\"" + code + "\"}")
                .build();
        //执行发送
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = null;
        try {


            resp = response.get();
        } catch (Exception e) {


            e.printStackTrace();
            //出现错误
            Map<String, Object> result = new HashMap<>();
            result.put("error", e.getMessage());
            return result;
        }

        //处理结果
        ObjectMapper objectMapper = new ObjectMapper();
        String json;
        try {
            json = objectMapper.writeValueAsString(resp);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", "Failed to convert response to JSON: " + e.getMessage());
            return errorResult;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("result", json);
        client.close();
        return result;
    }
}
